import 'package:enterprise_v6_app/app/components/custom_modele/custom_card.dart';
import 'package:enterprise_v6_app/app/components/custom_modele/custom_dropdown_selection.dart';
import 'package:enterprise_v6_app/app/components/custom_modele/custom_table.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_time_period.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_title_chart_page.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/list.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/data/common/charts_pie.dart';
import 'package:enterprise_v6_app/app/modules/application/education/home/home_controller.dart';
import 'package:enterprise_v6_app/app/modules/application/education/home/model.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

class EducationHomeView extends StatelessWidget {
  EducationHomeView({required this.type, super.key});

  final EducationHomeSummaryType type;

  final controller = Get.put(EducationHomeController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: controller,
      builder: (_) {
        return Scaffold(
          body: _buildBody(),
        );
      },
    );
  }

  Widget _buildBody() {
    return Container(
      decoration: BoxDecoration(
        color: AppColors.Pure_gray_bg,
        borderRadius: BorderRadius.circular(10.w),
      ),
      padding: EdgeInsets.all(13.w),
      child: ListView(
        children: _buildContent(),
      ),
    );
  }

  List<Widget> _buildContent() {
    switch (type) {
      case EducationHomeSummaryType.personal:
        return [
          _buildLesson(),
          AppGaps.vGap10,
          _buildPlan(),
          AppGaps.vGap50,
        ];
      case EducationHomeSummaryType.whole:
        return [
          CustomCard(
            content: CustomSelectTimePeriod(
              onConfirm: (start, end) {
                controller.startDate = start;
                controller.endDate = end;
                controller.refreshTimeAndDepartmentRelativeData();
              },
            ),
            padding: EdgeInsets.zero,
          ),
          AppGaps.vGap10,
          CustomCard(
            content: CustomDropdownSelection(
              hintText: '请选择部门',
              onCallBack: () {
                controller.showSelect(() {});
              },
            ),
            padding: EdgeInsets.zero,
          ),
          AppGaps.vGap10,
          _buildAllSummary(),
          AppGaps.vGap10,
          _buildPassRate(),
          AppGaps.vGap10,
          _buildTestRank(),
          AppGaps.vGap10,
          _buildLessonTimeRank(),
          AppGaps.vGap50,
        ];
    }
  }

  /// 课程情况统计
  Widget _buildLesson() {
    return CustomTitleChartPage(
      title: '课程情况统计',
      child: Column(
        children: [
          Container(
            decoration: BoxDecoration(
              color: const Color(0x1A5C6DFF),
              borderRadius: BorderRadius.circular(7.w),
            ),
            padding: EdgeInsets.all(10.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: controller.lessonTop.keys
                  .map((e) {
                    final val = controller.lessonTop[e];
                    // ignore: unnecessary_cast
                    return Column(
                      children: [
                        Text(val ?? '0', style: const TextStyle(color: Colors.blue)),
                        Text(e, style: const TextStyle(color: Colors.blue)),
                      ],
                    ) as Widget;
                  })
                  .toList()
                  .joinWith(Container(
                    height: 24.w,
                    width: 1,
                    color: Colors.white,
                  )),
            ),
          ),
          AppGaps.vGap16,
          Row(
            children: [
              _buildLeadingLine(),
              AppGaps.hGap10,
              const Text('课程数量统计'),
            ],
          ),
          SizedBox(
            height: 120.w,
            child: SfCircularChart(
              legend: Legend(
                isVisible: true,
                height: 170.w.toString(),
                position: LegendPosition.right,
                overflowMode: LegendItemOverflowMode.none,
                legendItemBuilder: (String name, dynamic series, dynamic point, int idx) {
                  final item = controller.lessonCount[idx];
                  return _buildLegendItem(
                    idx,
                    item.color,
                    name,
                    item.y.toInt(),
                    height: 31.w,
                    top: 27.w,
                  );
                },
                toggleSeriesVisibility: false,
              ),
              series: <CircularSeries>[
                DoughnutSeries<ChartData, String>(
                  dataSource: controller.lessonCount,
                  pointColorMapper: (ChartData data, _) => data.color,
                  xValueMapper: (ChartData data, _) => data.x,
                  yValueMapper: (ChartData data, _) => data.y,
                  name: '课程数量统计',
                  dataLabelSettings: const DataLabelSettings(
                    isVisible: false,
                    labelPosition: ChartDataLabelPosition.inside,
                  ),
                  radius: '100%',
                  innerRadius: '75%',
                  enableTooltip: true,
                ),
              ],
              annotations: [
                if (controller.lessonCount.total == 0)
                  CircularChartAnnotation(
                    widget: SizedBox(
                      width: 77.w,
                      height: 77.w,
                      child: CircularProgressIndicator(
                        strokeWidth: 11.w,
                        value: 1,
                        valueColor: AlwaysStoppedAnimation<Color>(EducationHomeController.colors.first),
                      ),
                    ),
                  ),
              ],
            ),
          ),
          AppGaps.vGap16,
          Row(
            children: [
              _buildLeadingLine(),
              AppGaps.hGap10,
              const Text('课程完成情况'),
            ],
          ),
          SizedBox(
            height: 120.w,
            child: SfCircularChart(
              legend: Legend(
                isVisible: true,
                height: 170.w.toString(),
                position: LegendPosition.right,
                overflowMode: LegendItemOverflowMode.none,
                legendItemBuilder: (String name, dynamic series, dynamic point, int idx) {
                  final item = controller.lessonFinish[idx];
                  return _buildLegendItem(
                    idx,
                    item.color,
                    name,
                    item.y.toInt(),
                    height: 31.w,
                    top: 27.w,
                  );
                },
                toggleSeriesVisibility: false,
              ),
              series: <CircularSeries>[
                DoughnutSeries<ChartData, String>(
                  dataSource: controller.lessonFinish,
                  pointColorMapper: (ChartData data, _) => data.color,
                  xValueMapper: (ChartData data, _) => data.x,
                  yValueMapper: (ChartData data, _) => data.y,
                  name: '课程完成情况',
                  dataLabelSettings: const DataLabelSettings(
                    isVisible: false,
                    labelPosition: ChartDataLabelPosition.inside,
                  ),
                  radius: '100%',
                  innerRadius: '75%',
                  enableTooltip: true,
                ),
              ],
              annotations: [
                if (controller.lessonFinish.total == 0)
                  CircularChartAnnotation(
                    widget: SizedBox(
                      width: 77.w,
                      height: 77.w,
                      child: CircularProgressIndicator(
                        strokeWidth: 11.w,
                        value: 1,
                        valueColor: AlwaysStoppedAnimation<Color>(EducationHomeController.colors.first),
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 计划情况统计
  Widget _buildPlan() {
    return CustomTitleChartPage(
      title: '计划情况统计',
      child: Column(
        children: [
          Container(
            decoration: BoxDecoration(
              color: const Color(0x1A5C6DFF),
              borderRadius: BorderRadius.circular(7.w),
            ),
            padding: EdgeInsets.all(10.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: controller.planTop.keys
                  .map((e) {
                    final val = controller.lessonTop[e];
                    // ignore: unnecessary_cast
                    return Column(
                      children: [
                        Text(val ?? '0', style: const TextStyle(color: Colors.blue)),
                        Text(e, style: const TextStyle(color: Colors.blue)),
                      ],
                    ) as Widget;
                  })
                  .toList()
                  .joinWith(Container(
                    height: 24.w,
                    width: 1,
                    color: Colors.white,
                  )),
            ),
          ),
          AppGaps.vGap16,
          _buildSmallTitle('培训途径统计'),
          SizedBox(
            height: 120.w,
            child: SfCircularChart(
              legend: Legend(
                isVisible: true,
                height: 170.w.toString(),
                position: LegendPosition.right,
                overflowMode: LegendItemOverflowMode.none,
                legendItemBuilder: (String name, dynamic series, dynamic point, int idx) {
                  final item = controller.teachType[idx];
                  return _buildLegendItem(
                    idx,
                    item.color,
                    name,
                    item.y.toInt(),
                    height: 31.w,
                    top: 27.w,
                  );
                },
                toggleSeriesVisibility: false,
              ),
              series: <CircularSeries>[
                DoughnutSeries<ChartData, String>(
                  dataSource: controller.teachType,
                  pointColorMapper: (ChartData data, _) => data.color,
                  xValueMapper: (ChartData data, _) => data.x,
                  yValueMapper: (ChartData data, _) => data.y,
                  name: '培训类型统计',
                  dataLabelSettings: const DataLabelSettings(
                    isVisible: false,
                    labelPosition: ChartDataLabelPosition.inside,
                  ),
                  radius: '100%',
                  innerRadius: '75%',
                  enableTooltip: true,
                ),
              ],
              annotations: [
                if (controller.teachType.total == 0)
                  CircularChartAnnotation(
                    widget: SizedBox(
                      width: 77.w,
                      height: 77.w,
                      child: CircularProgressIndicator(
                        strokeWidth: 11.w,
                        value: 1,
                        valueColor: AlwaysStoppedAnimation<Color>(EducationHomeController.colors.first),
                      ),
                    ),
                  ),
              ],
            ),
          ),
          AppGaps.vGap16,
          _buildSmallTitle('培训完成情况'),
          SizedBox(
            height: 120.w,
            child: SfCircularChart(
              legend: Legend(
                isVisible: true,
                height: 170.w.toString(),
                position: LegendPosition.right,
                overflowMode: LegendItemOverflowMode.none,
                legendItemBuilder: (String name, dynamic series, dynamic point, int idx) {
                  final item = controller.teachFinish[idx];
                  return _buildLegendItem(
                    idx,
                    item.color,
                    name,
                    item.y.toInt(),
                    height: 31.w,
                    top: 27.w,
                  );
                },
                toggleSeriesVisibility: false,
              ),
              series: <CircularSeries>[
                DoughnutSeries<ChartData, String>(
                  dataSource: controller.teachFinish,
                  pointColorMapper: (ChartData data, _) => data.color,
                  xValueMapper: (ChartData data, _) => data.x,
                  yValueMapper: (ChartData data, _) => data.y,
                  name: '计划完成情况',
                  dataLabelSettings: const DataLabelSettings(
                    isVisible: false,
                    labelPosition: ChartDataLabelPosition.inside,
                  ),
                  radius: '100%',
                  innerRadius: '75%',
                  enableTooltip: true,
                ),
              ],
              annotations: [
                if (controller.teachFinish.total == 0)
                  CircularChartAnnotation(
                    widget: SizedBox(
                      width: 77.w,
                      height: 77.w,
                      child: CircularProgressIndicator(
                        strokeWidth: 11.w,
                        value: 1,
                        valueColor: AlwaysStoppedAnimation<Color>(EducationHomeController.colors.first),
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 综合统计
  Widget _buildAllSummary() {
    return CustomTitleChartPage(
      title: '综合统计',
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _buildSmallTitle('培训覆盖率'),
          AppGaps.vGap10,
          controller.teachCount.build,
          AppGaps.vGap10,
          _buildSmallTitle('课时达标率'),
          AppGaps.vGap10,
          controller.timePassRate.build,
          AppGaps.vGap10,
          _buildSmallTitle('考核合格率'),
          AppGaps.vGap10,
          controller.testPassRate.build,
        ],
      ),
    );
  }

  /// 入厂三级培训与承包商培训通过率
  Widget _buildPassRate() {
    return CustomTitleChartPage(
      title: '入厂三级培训与承包商培训通过率',
      child: Column(
        children: [
          Container(
            decoration: BoxDecoration(
              color: const Color(0x1A5C6DFF),
              borderRadius: BorderRadius.circular(7.w),
            ),
            padding: EdgeInsets.all(10.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: controller.factoryTrain.keys
                  .map((e) {
                    final val = controller.factoryTrain[e];
                    // ignore: unnecessary_cast
                    return Column(
                      children: [
                        Text(
                          (val ?? 0).toString(),
                          style: const TextStyle(color: Colors.blue),
                        ),
                        Text(e, style: const TextStyle(color: Colors.blue)),
                      ],
                    ) as Widget;
                  })
                  .toList()
                  .joinWith(Container(
                    height: 24.w,
                    width: 1,
                    color: Colors.white,
                  )),
            ),
          ),
          AppGaps.vGap16,
          _buildSmallTitle('承包商人员培训'),
          controller.factoryTrainRate.build,
        ],
      ),
    );
  }

  /// 培训考核排名
  Widget _buildTestRank() {
    return CustomCard(
      title: '培训考核排名',
      content: CustomTable(
        xLen: 4,
        yLen: 3,
        color: const Color(0x335C6DFF),
        padding: EdgeInsets.all(3.w),
        cellPadding: EdgeInsets.symmetric(vertical: 7.w),
        cellBuilder: (x, y) {
          return Text(
            getRankCellStr(true, x, y) ?? '',
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 12.w, color: const Color(0xFF818499)),
          );
        },
        headBuilder: (x) {
          const titles = ['名称', '总平均分', '姓名', '职务-部门'];
          return Text(
            titles[x],
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 12.w, color: Colors.black),
          );
        },
      ),
    );
  }

  String? getRankCellStr(bool isTest, int x, int y) {
    final rank = isTest ? controller.testRank : controller.learnTimeRank;
    if (y > rank.length - 1) return null;
    final item = rank[y];
    switch (x) {
      case 0:
        return y.toString().padLeft(2, '0');
      case 1:
        return item.averageScore.toString();
      case 2:
        return item.userName;
      case 3:
        return item.departmentName;
    }
    return null;
  }

  /// 培训完成学时排名
  Widget _buildLessonTimeRank() {
    return CustomCard(
      title: '培训完成学时排名',
      content: CustomTable(
        xLen: 4,
        yLen: 3,
        color: const Color(0x335C6DFF),
        padding: EdgeInsets.all(3.w),
        cellPadding: EdgeInsets.symmetric(vertical: 7.w),
        cellBuilder: (x, y) {
          return Text(
            getRankCellStr(false, x, y) ?? '',
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 12.w, color: const Color(0xFF818499)),
          );
        },
        headBuilder: (x) {
          const titles = ['名称', '总平均分', '姓名', '职务-部门'];
          return Text(
            titles[x],
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 12.w, color: Colors.black),
          );
        },
      ),
    );
  }

  Widget _buildLeadingLine() {
    return Container(
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Color(0xFF5C6DFF), Color(0xFFB0ABFB)],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
        borderRadius: BorderRadius.circular(3.w),
      ),
      height: 12.w,
      width: 4.w,
    );
  }

  Widget _buildSmallTitle(String title) {
    return Row(
      children: [
        _buildLeadingLine(),
        AppGaps.hGap10,
        Text(title),
      ],
    );
  }

  Widget _buildLegendItem(int idx, Color? color, String name, int count, {double? height, double? top}) {
    final child = Container(
      width: 100.w,
      height: height ?? 23.w,
      alignment: Alignment.center,
      child: Row(
        children: [
          Container(
            width: 10.w,
            height: 10.w,
            margin: EdgeInsets.only(right: 5.w),
            padding: EdgeInsets.all(2.w),
            decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(5.w)),
            child: Container(
              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(5.w)),
            ),
          ),
          Text(
            name,
            style: TextStyle(fontSize: 12.w, fontWeight: FontWeight.w400, color: const Color(0xffA0A7B5)),
          ),
          const Spacer(),
          Text(
            '$count',
            style: TextStyle(
              fontSize: 12.sp,
              fontWeight: FontWeight.w400,
              color: Colors.black,
            ),
          ),
        ],
      ),
    );
    if (idx == 0) {
      return Padding(padding: EdgeInsets.only(top: top ?? 0.w), child: child);
    }
    return child;
  }

  Widget _buildBtn(String name, void Function() onTap) {
    return Container(
      width: 87.w,
      height: 40.w,
      decoration: BoxDecoration(
        border: Border.all(color: AppColors.blue_button, width: 1.3.w),
        borderRadius: BorderRadius.circular(37.w),
      ),
      child: Center(
        child: Text(
          name,
          style: TextStyle(
            fontSize: 16.w,
            color: AppColors.blue_button,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    ).clickOnce(onTap);
  }
}
